package net.gz01.wallet.web.controller.customer;

import net.gz01.wallet.common.TopBank;
import net.gz01.wallet.web.controller.BaseController;
import net.gz01.wallet.web.model.*;

public class ContactsController extends BaseController {

	public void index() {
		MerchUser merchUser = (MerchUser) getSession().getAttribute(MerchUser.SessionKey);
		setAttr("list", Contacts.dao.select(merchUser.getMerchCode()));
		setAttr("banks", TopBank.topBankList);
		render("contacts.html");
	}

	public void save() {
		MerchUser merchUser = (MerchUser) getSession().getAttribute(MerchUser.SessionKey);
		Contacts contacts = getModel(Contacts.class, "");
		if ("bankCard".equals(contacts.getAccountType())) {
			TopBank bank = TopBank.getByShortEnName(contacts.getBankEnglishLetters());
			contacts.setBankName(bank.getBankName());
			contacts.setOpeningBankNo(bank.getBankNo());
//			Merch merch = Merch.dao.selectByMerchCode(merchUser.getMerchCode());
//			if (merch.getName().equals(contacts.getAccountName())) {
//				contacts.setIsSelf(true);
//			} else {
//				contacts.setIsSelf(false);
//			}
		} else {//wallet//判断添加的 钱包账号是否合法
			contacts.setIsSelf(false);
			if(merchUser.getMerchCode().equals(contacts.getAccountNo())){
				renderFail("不能添加自己的钱包!");
				return;
			}

			Merch other = Merch.dao.selectByMerchCode(contacts.getAccountNo());
			if(other == null){
				renderFail("添加钱包用户错误:" + contacts.getAccountNo() + "不存在此钱包用户,请联系管理员!");
				return;
			}
			if(!other.getName().equals(contacts.getAccountName())){
				renderFail("添加钱包用户错误:" + contacts.getAccountNo() + "钱包账户名称错误!");
				return;
			}
			if(null==other.getIsSign() || null == other.getIsVerify() || !other.getIsSign() || !other.getIsVerify() ){
				renderFail("添加钱包用户错误:" + contacts.getAccountNo() + "没有开通钱包功能，请先联系实名网签激活钱包功能");
				return;
			}
		}
		contacts.setMerchCode(merchUser.getMerchCode());

		Merch myMerch = Merch.dao.selectByMerchCode(merchUser.getMerchCode());
		contacts.setMerchName(myMerch.getName());

		// 新增
		if(contacts.getId() == null) {
			if(Contacts.dao.exists(merchUser.getMerchCode(), contacts.getAccountType(), contacts.getAccountNo())) {
				renderFail("[" + contacts.getAccountType() + "]" + contacts.getAccountNo() + "已存在");
				return;
			}
			contacts.save();
		}
		// 修改
		else {
			contacts.update();
		}

		renderSuccess();
	}

	public void delete() {
		MerchUser merchUser = (MerchUser) getSession().getAttribute(MerchUser.SessionKey);
		Contacts.dao.delete(merchUser.getMerchCode(), getParaToLong("id"));
		renderSuccess();
	}

	public void find() {
		MerchUser merchUser = (MerchUser) getSession().getAttribute(MerchUser.SessionKey);
		renderJson(Contacts.dao.select(merchUser.getMerchCode(), getParaToLong("id")));
	}

	/**
	 * 查询卡BIN
	 */
	public void cardbin() {
		// 数据库中卡BIN长度最短2位（只有一条记录，正常来说没用）// 65 Discover Financial Services，I 26290840 2
		// 数据库中卡BIN长度最短12位
		String cardNo = getPara("cardNo");
		CardBin cardBin = CardBin.search(cardNo);
		renderJson(cardBin);
	}
}
